home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / tokenize.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  14KB  |  433 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Tokenization help for Python programs.
  5.  
  6. generate_tokens(readline) is a generator that breaks a stream of
  7. text into Python tokens.  It accepts a readline-like method which is called
  8. repeatedly to get the next line of input (or "" for EOF).  It generates
  9. 5-tuples with these members:
  10.  
  11.     the token type (see token.py)
  12.     the token (a string)
  13.     the starting (row, column) indices of the token (a 2-tuple of ints)
  14.     the ending (row, column) indices of the token (a 2-tuple of ints)
  15.     the original line (string)
  16.  
  17. It is designed to match the working of the Python tokenizer exactly, except
  18. that it produces COMMENT tokens for comments and gives type OP for all
  19. operators
  20.  
  21. Older entry points
  22.     tokenize_loop(readline, tokeneater)
  23.     tokenize(readline, tokeneater=printtoken)
  24. are the same, except instead of generating tokens, tokeneater is a callback
  25. function to which the 5 fields described above are passed as 5 arguments,
  26. each time a new token is found.'''
  27. __author__ = 'Ka-Ping Yee <ping@lfw.org>'
  28. __credits__ = 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro, Raymond Hettinger'
  29. import string
  30. import re
  31. from token import *
  32. import token
  33. __all__ = _[1] + [
  34.     'COMMENT',
  35.     'tokenize',
  36.     'generate_tokens',
  37.     'NL',
  38.     'untokenize']
  39. del x
  40. del token
  41. COMMENT = N_TOKENS
  42. tok_name[COMMENT] = 'COMMENT'
  43. NL = N_TOKENS + 1
  44. tok_name[NL] = 'NL'
  45. N_TOKENS += 2
  46.  
  47. def group(*choices):
  48.     return '(' + '|'.join(choices) + ')'
  49.  
  50.  
  51. def any(*choices):
  52.     return group(*choices) + '*'
  53.  
  54.  
  55. def maybe(*choices):
  56.     return group(*choices) + '?'
  57.  
  58. Whitespace = '[ \\f\\t]*'
  59. Comment = '#[^\\r\\n]*'
  60. Ignore = Whitespace + any('\\\\\\r?\\n' + Whitespace) + maybe(Comment)
  61. Name = '[a-zA-Z_]\\w*'
  62. Hexnumber = '0[xX][\\da-fA-F]+[lL]?'
  63. Octnumber = '(0[oO][0-7]+)|(0[0-7]*)[lL]?'
  64. Binnumber = '0[bB][01]+[lL]?'
  65. Decnumber = '[1-9]\\d*[lL]?'
  66. Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
  67. Exponent = '[eE][-+]?\\d+'
  68. Pointfloat = group('\\d+\\.\\d*', '\\.\\d+') + maybe(Exponent)
  69. Expfloat = '\\d+' + Exponent
  70. Floatnumber = group(Pointfloat, Expfloat)
  71. Imagnumber = group('\\d+[jJ]', Floatnumber + '[jJ]')
  72. Number = group(Imagnumber, Floatnumber, Intnumber)
  73. Single = "[^'\\\\]*(?:\\\\.[^'\\\\]*)*'"
  74. Double = '[^"\\\\]*(?:\\\\.[^"\\\\]*)*"'
  75. Single3 = "[^'\\\\]*(?:(?:\\\\.|'(?!''))[^'\\\\]*)*'''"
  76. Double3 = '[^"\\\\]*(?:(?:\\\\.|"(?!""))[^"\\\\]*)*"""'
  77. Triple = group("[uU]?[rR]?'''", '[uU]?[rR]?"""')
  78. String = group("[uU]?[rR]?'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*'", '[uU]?[rR]?"[^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*"')
  79. Operator = group('\\*\\*=?', '>>=?', '<<=?', '<>', '!=', '//=?', '[+\\-*/%&|^=<>]=?', '~')
  80. Bracket = '[][(){}]'
  81. Special = group('\\r?\\n', '[:;.,`@]')
  82. Funny = group(Operator, Bracket, Special)
  83. PlainToken = group(Number, Funny, String, Name)
  84. Token = Ignore + PlainToken
  85. ContStr = group("[uU]?[rR]?'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*" + group("'", '\\\\\\r?\\n'), '[uU]?[rR]?"[^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*' + group('"', '\\\\\\r?\\n'))
  86. PseudoExtras = group('\\\\\\r?\\n', Comment, Triple)
  87. PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
  88. (tokenprog, pseudoprog, single3prog, double3prog) = map(re.compile, (Token, PseudoToken, Single3, Double3))
  89. endprogs = {
  90.     "'": re.compile(Single),
  91.     '"': re.compile(Double),
  92.     "'''": single3prog,
  93.     '"""': double3prog,
  94.     "r'''": single3prog,
  95.     'r"""': double3prog,
  96.     "u'''": single3prog,
  97.     'u"""': double3prog,
  98.     "ur'''": single3prog,
  99.     'ur"""': double3prog,
  100.     "R'''": single3prog,
  101.     'R"""': double3prog,
  102.     "U'''": single3prog,
  103.     'U"""': double3prog,
  104.     "uR'''": single3prog,
  105.     'uR"""': double3prog,
  106.     "Ur'''": single3prog,
  107.     'Ur"""': double3prog,
  108.     "UR'''": single3prog,
  109.     'UR"""': double3prog,
  110.     "b'''": single3prog,
  111.     'b"""': double3prog,
  112.     "br'''": single3prog,
  113.     'br"""': double3prog,
  114.     "B'''": single3prog,
  115.     'B"""': double3prog,
  116.     "bR'''": single3prog,
  117.     'bR"""': double3prog,
  118.     "Br'''": single3prog,
  119.     'Br"""': double3prog,
  120.     "BR'''": single3prog,
  121.     'BR"""': double3prog,
  122.     'r': None,
  123.     'R': None,
  124.     'u': None,
  125.     'U': None,
  126.     'b': None,
  127.     'B': None }
  128. triple_quoted = { }
  129. for t in ("'''", '"""', "r'''", 'r"""', "R'''", 'R"""', "u'''", 'u"""', "U'''", 'U"""', "ur'''", 'ur"""', "Ur'''", 'Ur"""', "uR'''", 'uR"""', "UR'''", 'UR"""', "b'''", 'b"""', "B'''", 'B"""', "br'''", 'br"""', "Br'''", 'Br"""', "bR'''", 'bR"""', "BR'''", 'BR"""'):
  130.     triple_quoted[t] = t
  131.  
  132. single_quoted = { }
  133. for t in ("'", '"', "r'", 'r"', "R'", 'R"', "u'", 'u"', "U'", 'U"', "ur'", 'ur"', "Ur'", 'Ur"', "uR'", 'uR"', "UR'", 'UR"', "b'", 'b"', "B'", 'B"', "br'", 'br"', "Br'", 'Br"', "bR'", 'bR"', "BR'", 'BR"'):
  134.     single_quoted[t] = t
  135.  
  136. tabsize = 8
  137.  
  138. class TokenError(Exception):
  139.     pass
  140.  
  141.  
  142. class StopTokenizing(Exception):
  143.     pass
  144.  
  145.  
  146. def printtoken(type, token, srow_scol, erow_ecol, line):
  147.     (srow, scol) = srow_scol
  148.     (erow, ecol) = erow_ecol
  149.     print '%d,%d-%d,%d:\t%s\t%s' % (srow, scol, erow, ecol, tok_name[type], repr(token))
  150.  
  151.  
  152. def tokenize(readline, tokeneater = printtoken):
  153.     '''
  154.     The tokenize() function accepts two parameters: one representing the
  155.     input stream, and one providing an output mechanism for tokenize().
  156.  
  157.     The first parameter, readline, must be a callable object which provides
  158.     the same interface as the readline() method of built-in file objects.
  159.     Each call to the function should return one line of input as a string.
  160.  
  161.     The second parameter, tokeneater, must also be a callable object. It is
  162.     called once for each token, with five arguments, corresponding to the
  163.     tuples generated by generate_tokens().
  164.     '''
  165.     
  166.     try:
  167.         tokenize_loop(readline, tokeneater)
  168.     except StopTokenizing:
  169.         pass
  170.  
  171.  
  172.  
  173. def tokenize_loop(readline, tokeneater):
  174.     for token_info in generate_tokens(readline):
  175.         tokeneater(*token_info)
  176.     
  177.  
  178.  
  179. class Untokenizer:
  180.     
  181.     def __init__(self):
  182.         self.tokens = []
  183.         self.prev_row = 1
  184.         self.prev_col = 0
  185.  
  186.     
  187.     def add_whitespace(self, start):
  188.         (row, col) = start
  189.         if not row <= self.prev_row:
  190.             raise AssertionError
  191.         col_offset = col - self.prev_col
  192.         if col_offset:
  193.             self.tokens.append(' ' * col_offset)
  194.         
  195.  
  196.     
  197.     def untokenize(self, iterable):
  198.         for t in iterable:
  199.             if len(t) == 2:
  200.                 self.compat(t, iterable)
  201.                 break
  202.             
  203.             (tok_type, token, start, end, line) = t
  204.             self.add_whitespace(start)
  205.             self.tokens.append(token)
  206.             (self.prev_row, self.prev_col) = end
  207.             if tok_type in (NEWLINE, NL):
  208.                 self.prev_row += 1
  209.                 self.prev_col = 0
  210.                 continue
  211.             self
  212.         
  213.         return ''.join(self.tokens)
  214.  
  215.     
  216.     def compat(self, token, iterable):
  217.         startline = False
  218.         indents = []
  219.         toks_append = self.tokens.append
  220.         (toknum, tokval) = token
  221.         if toknum in (NAME, NUMBER):
  222.             tokval += ' '
  223.         
  224.         if toknum in (NEWLINE, NL):
  225.             startline = True
  226.         
  227.         prevstring = False
  228.         for tok in iterable:
  229.             (toknum, tokval) = tok[:2]
  230.             if toknum in (NAME, NUMBER):
  231.                 tokval += ' '
  232.             
  233.             if toknum == STRING:
  234.                 if prevstring:
  235.                     tokval = ' ' + tokval
  236.                 
  237.                 prevstring = True
  238.             else:
  239.                 prevstring = False
  240.             if toknum == INDENT:
  241.                 indents.append(tokval)
  242.                 continue
  243.             elif toknum == DEDENT:
  244.                 indents.pop()
  245.                 continue
  246.             elif toknum in (NEWLINE, NL):
  247.                 startline = True
  248.             elif startline and indents:
  249.                 toks_append(indents[-1])
  250.                 startline = False
  251.             
  252.             toks_append(tokval)
  253.         
  254.  
  255.  
  256.  
  257. def untokenize(iterable):
  258.     '''Transform tokens back into Python source code.
  259.  
  260.     Each element returned by the iterable must be a token sequence
  261.     with at least two elements, a token number and token value.  If
  262.     only two tokens are passed, the resulting output is poor.
  263.  
  264.     Round-trip invariant for full input:
  265.         Untokenized source will match input source exactly
  266.  
  267.     Round-trip invariant for limited intput:
  268.         # Output text will tokenize the back to the input
  269.         t1 = [tok[:2] for tok in generate_tokens(f.readline)]
  270.         newcode = untokenize(t1)
  271.         readline = iter(newcode.splitlines(1)).next
  272.         t2 = [tok[:2] for tok in generate_tokens(readline)]
  273.         assert t1 == t2
  274.     '''
  275.     ut = Untokenizer()
  276.     return ut.untokenize(iterable)
  277.  
  278.  
  279. def generate_tokens(readline):
  280.     '''
  281.     The generate_tokens() generator requires one argment, readline, which
  282.     must be a callable object which provides the same interface as the
  283.     readline() method of built-in file objects. Each call to the function
  284.     should return one line of input as a string.  Alternately, readline
  285.     can be a callable function terminating with StopIteration:
  286.         readline = open(myfile).next    # Example of alternate readline
  287.  
  288.     The generator produces 5-tuples with these members: the token type; the
  289.     token string; a 2-tuple (srow, scol) of ints specifying the row and
  290.     column where the token begins in the source; a 2-tuple (erow, ecol) of
  291.     ints specifying the row and column where the token ends in the source;
  292.     and the line on which the token was found. The line passed is the
  293.     logical line; continuation lines are included.
  294.     '''
  295.     lnum = parenlev = continued = 0
  296.     namechars = string.ascii_letters + '_'
  297.     numchars = '0123456789'
  298.     (contstr, needcont) = ('', 0)
  299.     contline = None
  300.     indents = [
  301.         0]
  302.     while None:
  303.         
  304.         try:
  305.             line = readline()
  306.         except StopIteration:
  307.             line = ''
  308.  
  309.         lnum = lnum + 1
  310.         pos = 0
  311.         max = len(line)
  312.         if contstr:
  313.             if not line:
  314.                 raise TokenError, ('EOF in multi-line string', strstart)
  315.             line
  316.             endmatch = endprog.match(line)
  317.             if endmatch:
  318.                 pos = end = endmatch.end(0)
  319.                 yield (STRING, contstr + line[:end], strstart, (lnum, end), contline + line)
  320.                 (contstr, needcont) = ('', 0)
  321.                 contline = None
  322.             elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
  323.                 yield (ERRORTOKEN, contstr + line, strstart, (lnum, len(line)), contline)
  324.                 contstr = ''
  325.                 contline = None
  326.                 continue
  327.             else:
  328.                 contstr = contstr + line
  329.                 contline = contline + line
  330.         elif parenlev == 0 and not continued:
  331.             if not line:
  332.                 break
  333.             
  334.             column = 0
  335.             while pos < max:
  336.                 if line[pos] == ' ':
  337.                     column = column + 1
  338.                 elif line[pos] == '\t':
  339.                     column = (column / tabsize + 1) * tabsize
  340.                 elif line[pos] == '\x0c':
  341.                     column = 0
  342.                 else:
  343.                     break
  344.                 pos = pos + 1
  345.             if pos == max:
  346.                 break
  347.             
  348.             if line[pos] in '#\r\n':
  349.                 if line[pos] == '#':
  350.                     comment_token = line[pos:].rstrip('\r\n')
  351.                     nl_pos = pos + len(comment_token)
  352.                     yield (COMMENT, comment_token, (lnum, pos), (lnum, pos + len(comment_token)), line)
  353.                     yield (NL, line[nl_pos:], (lnum, nl_pos), (lnum, len(line)), line)
  354.                     continue
  355.                 yield ((NL, COMMENT)[line[pos] == '#'], line[pos:], (lnum, pos), (lnum, len(line)), line)
  356.                 continue
  357.             
  358.             if column > indents[-1]:
  359.                 indents.append(column)
  360.                 yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
  361.             
  362.             while column < indents[-1]:
  363.                 if column not in indents:
  364.                     raise IndentationError('unindent does not match any outer indentation level', ('<tokenize>', lnum, pos, line))
  365.                 column not in indents
  366.                 indents = indents[:-1]
  367.                 yield (DEDENT, '', (lnum, pos), (lnum, pos), line)
  368.         elif not line:
  369.             raise TokenError, ('EOF in multi-line statement', (lnum, 0))
  370.         
  371.         continued = 0
  372.         while pos < max:
  373.             pseudomatch = pseudoprog.match(line, pos)
  374.             if pseudomatch:
  375.                 (start, end) = pseudomatch.span(1)
  376.                 spos = (lnum, start)
  377.                 epos = (lnum, end)
  378.                 pos = end
  379.                 token = line[start:end]
  380.                 initial = line[start]
  381.                 if (initial in numchars or initial == '.') and token != '.':
  382.                     yield (NUMBER, token, spos, epos, line)
  383.                 elif initial in '\r\n':
  384.                     yield (None if parenlev > 0 else NEWLINE, token, spos, epos, line)
  385.                 elif initial == '#':
  386.                     if not not token.endswith('\n'):
  387.                         raise AssertionError
  388.                     yield (COMMENT, token, spos, epos, line)
  389.                     not token.endswith('\n')
  390.                 elif token in triple_quoted:
  391.                     endprog = endprogs[token]
  392.                     endmatch = endprog.match(line, pos)
  393.                     if endmatch:
  394.                         pos = endmatch.end(0)
  395.                         token = line[start:pos]
  396.                         yield (STRING, token, spos, (lnum, pos), line)
  397.                     else:
  398.                         strstart = (lnum, start)
  399.                         contstr = line[start:]
  400.                         contline = line
  401.                         break
  402.                 elif initial in single_quoted and token[:2] in single_quoted or token[:3] in single_quoted:
  403.                     if token[-1] == '\n':
  404.                         strstart = (lnum, start)
  405.                         if not endprogs[initial] and endprogs[token[1]]:
  406.                             pass
  407.                         endprog = endprogs[token[2]]
  408.                         contstr = line[start:]
  409.                         needcont = 1
  410.                         contline = line
  411.                         break
  412.                     else:
  413.                         yield (STRING, token, spos, epos, line)
  414.                 elif initial in namechars:
  415.                     yield (NAME, token, spos, epos, line)
  416.                 elif initial == '\\':
  417.                     continued = 1
  418.                 elif initial in '([{':
  419.                     parenlev = parenlev + 1
  420.                 elif initial in ')]}':
  421.                     parenlev = parenlev - 1
  422.                 
  423.                 yield (OP, token, spos, epos, line)
  424.                 continue
  425.             yield (ERRORTOKEN, line[pos], (lnum, pos), (lnum, pos + 1), line)
  426.             pos = pos + 1
  427.         continue
  428.         for indent in indents[1:]:
  429.             yield (DEDENT, '', (lnum, 0), (lnum, 0), '')
  430.         
  431.     yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')
  432.  
  433.